// PartDBParameterFormerSet.cpp: implementation of the PartDBParameterFormerSet class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "PartDBParameterFormerSet.h"
#include "PropertyFactory.h"
#include "PropertyStack.h"
#include "PartFunctionDB.h"
#include "ProductCatalogManager.h"
#include "ProductCatalog.h"
#include "PersistentFacade.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace PropertySystem;
using namespace DAWrapper;

PartDBParameterFormerSet::PartDBParameterFormerSet()
{

}

PartDBParameterFormerSet::~PartDBParameterFormerSet()
{

}

BOOL PartDBParameterFormerSet::CreatePart(Part *part)
{
	ASSERT(part);
	CString strDataSource;
	ASSERT(!GetDataStandard().IsEmpty());

	JointSystem::ProductCatalog* pCatalog = NULL;
	pCatalog = JointSystem::ProductCatalogManager::Instance()->GetProductCatalog(this->GetDataStandard());
	ASSERT(pCatalog);
	strDataSource = pCatalog->DataSourceURI();
	ASSERT(!strDataSource.IsEmpty());

	_ConnectionPtr* pCon = DBConnectionManager::Instance()->GetConnectionPtrByUri(strDataSource);

	Standard* pStandard = GetPersistentFacade().GetStandardGenerator()->Generate(pCatalog);
	ASSERT(pStandard);

	CString strPropertyTable = pStandard->PropertyTable();
	ASSERT(!strPropertyTable.IsEmpty());

	GetPropertyTemplate(part, strPropertyTable, strDataSource);

	PartFunctionDB Function(part, *pCon);
	return Function.CreatePart();
}

void PartDBParameterFormerSet::GetPropertyTemplate(Part* part, const CString& strProperty, const CString& strSource)
{
	ASSERT(part);
	ASSERT(!strProperty.IsEmpty());
	ASSERT(!strSource.IsEmpty());

	PropertyStack& stack = PropertyFactory::Instance().GetProperty(part->GetCustomID(), 
		part->GetStandard());
	
	PropertyVariable* pVar = NULL;
	PropertyStack::Iterator *it = stack.NewIterator();
	for(it->Begin(); !it->End(); it->Next())
	{
		pVar = static_cast<PropertyVariable*>(it->Get());
		ASSERT(pVar);
		PropertyVariable* pTempVar = pVar->Clone();
		ASSERT(pTempVar);
		part->AddProperty(pTempVar);
	}
	delete it;
}
